<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai.css'

import { quillEditor } from 'vue-quill-editor'

export default {
  name: 'BianJi',
  props: ['yuanshuju'],
  components: {
    quillEditor
  },
  data () {
    return {
      jinyong: false,
      yuanshuju1: '',
      fileList: [],
      ruleForm: {
        title: '',
        fenlei: '',
        postdate: '',
        content: '',
        imgurl: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 5, max: 32, message: '长度在 5 到 32 个字符', trigger: 'blur' }
        ],
        fenlei: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        postdate: [
          { type: 'date', required: true, message: '请选择时间日期', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请填写正文', trigger: 'blur' }
        ]
      },
      editorOption: {
        placeholder: '在这里输入内容...',
        theme: 'snow',
        // scrollingContainer: true
        // snow：传统的工具栏主题，bubble：选中文本才会显示工具栏
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            [{ script: 'sub' }, { script: 'super' }], // 上标/下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ color: [] }, { background: [] }], // 字体颜色、背景颜色
            [{ font: [] }],
            [{ align: [] }],
            ['clean'], // 清除文本格式
            ['link', 'image', 'video'] // 链接、图片、视频
          ],
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.id) {
            console.log(this.ruleForm)
            const xiangying = this.$axios.put(`houtai/adminlist/${this.ruleForm.id}/`, JSON.stringify(this.ruleForm), { headers: { 'Content-Type': 'application/json' } })
            if (xiangying) {
              location.reload()
            }
          } else {
            // console.log(this.ruleForm)
            const reponse = this.$axios.post('houtai/adminlist/', JSON.stringify(this.ruleForm), { headers: { 'Content-Type': 'application/json' } })
            if (reponse) {
              location.reload()
            }
          }
        } else {
          alert('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    validate1 () {
      this.$refs.ruleForm.validateField('content')
    },
    handleImageUpload () {
      const input = document.createElement('input')
      input.setAttribute('type', 'file')
      input.setAttribute('accept', 'image/*')
      input.click()

      input.onchange = async () => {
        const file = input.files[0]
        // console.log(file)
        if (file) {
          const formData = new FormData()
          formData.append('image', file)
          // const img = formData.get('image')
          try {
            // console.dir(formData)
            const response = await this.$axios.post('/houtai/uploadimg/', formData)
            // console.log(response)
            if (response.url) {
              // 获取编辑器实例
              // console.log(response.url)
              const quill = this.$refs.quillEditor.quill
              const range = quill.getSelection()
              // 插入图片 URL
              quill.insertEmbed(range.index, 'image', response.url)
              // const html = `<img src="${response.url}" alt=""/>`
              // quill.clipboard.dangerouslyPasteHTML(range.index, html)
              // this.ruleForm.content = quill.root.innerHTML.replace(/\\"/g, '""')
              // let updatedContent = quill.root.innerHTML
              // updatedContent = updatedContent.replace(/\\"/g, '"') // 清除转义的双引号
              // updatedContent = updatedContent.replace(/\\'/g, "'") // 清除转义的单引号
              // updatedContent = updatedContent.replace(/\\\\/g, '\\') // 清除转义的反斜杠
              // 更新 ruleForm.content，避免转义字符
              // this.ruleForm.content = updatedContent
            } else {
              alert('服务器未返回图片 URL')
            }
          } catch (error) {
            console.error('图片上传失败:', error)
            alert('图片上传失败，请稍后重试！')
          }
        }
      }
    },
    async upload (param) {
      const file = param.file
      // console.log(file)
      if (file) {
        const formData = new FormData()
        formData.append('image', file)
        // const img = formData.get('image')
        try {
          // console.dir(formData)
          const response = await this.$axios.post('/houtai/uploadimg/', formData)
          // console.log(response)
          if (response.url) {
            // 获取编辑器实例
            // console.log(response.url)
            this.ruleForm.imgurl = response.url
            // console.log(this.ruleForm.imgurl)
          } else {
            alert('服务器未返回图片 URL')
          }
        } catch (error) {
          console.error('图片上传失败:', error)
          alert('图片上传失败，请稍后重试！')
        }
      }
    }
  },
  mounted () {
    // 获取 Quill 实例
    const quill = this.$refs.quillEditor.quill
    const toolbar = quill.getModule('toolbar')
    // 覆盖默认图片上传功能
    toolbar.addHandler('image', this.handleImageUpload)
  },
  watch: {
    async yuanshuju () {
      if (this.yuanshuju) {
        this.yuanshuju1 = await this.$axios.get(`houtai/adminlist/${this.yuanshuju}/`)
        // console.log(this.yuanshuju1)
        this.ruleForm = this.yuanshuju1
        // console.log(this.ruleForm)
        this.jinyong = true
      }
    }
  }
}
</script>

<template>
  <div class="bianji">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
             style="width: 70%;margin: 0 auto;">
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="fenlei">
        <el-select v-model="ruleForm.fenlei" placeholder="请选择分类">
          <el-option label="Django" value="1"></el-option>
          <el-option label="Vue" value="2"></el-option>
          <el-option label="Ajax" value="3"></el-option>
          <el-option label="随记" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间" required>
        <el-col :span="11">
          <el-form-item prop="postdate">
            <el-date-picker
              v-model="ruleForm.postdate"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="上传图片">
        <el-upload
          :disabled="jinyong"
          class="upload-demo"
          action=""
          :http-request="upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="正文" prop="desc">
        <quill-editor v-model="ruleForm.content"
                      ref="quillEditor"
                      :options="editorOption"
                      @blur="validate1"></quill-editor>
      </el-form-item>
      <el-form-item prop="content">
        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
      <!--      <div v-html="ruleForm.content"></div>-->
      <!--      <div>{{ ruleForm }}</div>-->
    </el-form>

  </div>
</template>

<style scoped lang="scss">
.binaji {
  display: flex;
  min-height: 1000px;
  background: #2c3e50;
}
</style>
